package com.jmm.neditor.utils.upload;

import com.aliyun.oss.OSSClient;
import com.jmm.neditor.utils.DateUtil;
import com.jmm.neditor.utils.UuidUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * AliyunOSSUtil class
 *
 * @author 蒋时华
 * @date 2018-5-8
 */
public class AliyunOSSUtil {

    private static OSSClient ossClient;
    private static String OSS_ENDPOINT = "oss-cn-shanghai.aliyuncs.com";
    private static String OSS_ACCESS_KEY_ID = "LTAI4S7oH1Sa5NHu";
    private static String OSS_ACCESS_KEY_SECRET = "xBgPu1S5bB7F0eu0W0J5twLdozQzkP";
    private static String OSS_BUCKET_NAME = "csh-test-001";

    private static OSSClient getOssClient() {
        if(ossClient==null){
            ossClient=new OSSClient(OSS_ENDPOINT,OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET);
        }
        return ossClient;
    }

    public static String uploadNeditorFile(MultipartFile file,String path, String fileSuffix) throws Exception {
        return upload(file.getInputStream(),path,fileSuffix);
    }

    private static String upload(InputStream in, String path, String fileSuffix) throws Exception {

        OSSClient ossClient=getOssClient();
        try {
            String folder=path+DateUtil.getDays()+"/";
            //判断是否存在文件夹
            boolean found = ossClient.doesObjectExist(OSS_BUCKET_NAME,folder );
            if(!found){
                ossClient.putObject(OSS_BUCKET_NAME, folder,new ByteArrayInputStream(new byte[0]));
            }
            String key=UuidUtil.get32UUID();
            String extName = fileSuffix;
            key=key+extName;
            ossClient.putObject(OSS_BUCKET_NAME,folder+key, in);
            return folder+key;
        } catch (Exception e) {
            throw e;
        }finally {
//            if (ossClient != null) {
//                ossClient.shutdown();
//            }
            if(in!=null){
                in.close();
            }
        }
    }


}
